package com.zx.filter;/**
 * Author:JasonZ
 * Data:2023/4/17
 */

import com.alibaba.fastjson.JSON;
import com.zx.constant.AuthorityConstant;
import com.zx.model.vo.LoginUserInfo;
import com.zx.util.TokenParseUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @program: ecommerce-parent
 * @description:全局过滤器
 * @author: JasonZ
 * @create: 2023-04-17 15:41
 **/
@Component
@Slf4j
public class AuthenticationFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求和响应
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String url = request.getURI().getPath();
        //白名单
        //是登录或者注册直接放行
        if (url.contains("/authority/login") || url.contains("/authority/register")) {
            return chain.filter(exchange);
        }
        //鉴权
        //取出请求头中的authentication
        String token = request.getHeaders().getFirst(AuthorityConstant.AUTHENTICATION_TOKEN_KEY);
        LoginUserInfo loginUserInfo = null;
        /*解析凭证*/
        try {
            loginUserInfo = TokenParseUtil.parseUserInfoFromToken(token);
            log.info("解析成功 loginUserInfo: [{}]", JSON.toJSONString(loginUserInfo));
        } catch (Exception e) {
            e.printStackTrace();
        }
        //凭证为空即为解析失败
        if (loginUserInfo == null) {
            log.error("凭证失效！或者已经被篡改");
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();  //设置请求结束，设置未授权的响应码
        }
        //鉴权通过 放行
        return chain.filter(exchange);
    }

    /*定义执行过滤器的 越小越先执行*/
    @Override
    public int getOrder() {
        return HIGHEST_PRECEDENCE + 1;
    }
}
